/* itfreer v1.1
 * wdp web应用开发平台
 * 此类定义ArcGIS的基础逻辑，包括绘制器，查询器，定位器，转换器等。
 */
;
/**
 * 初始化ArcGIS变量
 */
(function() {
	
	this.arcGISObject = {};
	this.hasInitFinsh = false;
	this.initFinshEvent = null;

	require(["esri/map",

		"esri/layers/WMSLayer",
		"esri/layers/WMTSLayer", 

        "esri/tasks/geometry",
        "esri/tasks/query",
		"esri/tasks/QueryTask",

		 "esri/graphic",
		 "esri/urlUtils",
		 "esri/units",
			
		"esri/config",
		"esri/geometry/Point",
		"esri/geometry/Circle",
		"esri/geometry/Extent",
		"esri/SpatialReference",
		
		"esri/toolbars/navigation",
		"esri/toolbars/draw",

		"esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
         "esri/dijit/Scalebar",
		"dojo/parser",
		"dojo/domReady!"],
	function (Map,
	          bMapVeclayer, bMapImglayer, bMapAnolayer,
	          tdMapAnnoLayer, tdMapLayer, tdMapImgAnnoLayer, tdMapImgLayer){

		this.hasInitFinsh = true;

	    // arcgis的proxy地址
		esriConfig.defaults.io.proxyUrl = getBasePath() + "/gis/proxy.do";

		if(this.initFinshEvent){
			this.initFinshEvent();
		}
	});
}).call(this);

/* 
 * 定义itfreer.arcgis.core核心模块，提供一些基础地理算法
 */
(function(window, angular, undefined){
	/* 
	 * 定义ArcGIS的核心模块，提供一些基础地理算法
	 */
	var itfreerarcgiscoreModule = angular.module('itfreer.arcgis.core', ['itfreer.core']);

	/* 
	 * 定义gis变量
	 */
	itfreerarcgiscoreModule.value('$gisObject', {
		// 地理坐标系统
		dlwkid : 4326,
		// 投影坐标系统
		tywkid : 102100,
		// 当前的地图是否为地理坐标系统
		mapisdlwkid : true,
		// 主地图
		map : null,
		// 基础地址图层集
		BaseTiledLayer : {},
		// 基础影像图层集
		BaseImageLayer : {},
		// 专题图层集
		Services : {},
		// 导航工具条
		navToolbar : null,
		// 绘制工具条
		drawToolbars : null,
		// 定位器
		locator : null,
		// 当前的定位级别
		locatorLevel : null,
		// 当前的定位地址名称
		locatorAddress : "",
		// geometry服务
		geometryService : null,
		// printing服务
		printingService : null,
		/* 
		 * 定义ArcGIS的各种样式
		 */
		styleConfig : {
			/* 
			 * 绘制样式
			 */
			drawStyle : {
				fillColor : createColorFromHex("#ff0000"),
				fillOpacity : 0.8,
				strokeColor : createColorFromHex("#ff0000"),
				strokeWidth : 2
			},
			/* 
			 * 高亮默认样式
			 */
			highLightDefaultStyle : {
				fillColor : createColorFromHex("#FBDF55"),
				fillOpacity : 0.5,
				strokeColor : createColorFromHex("#666666"),
				strokeWidth : 4
			},
			/* 
			 * 高亮选择样式
			 */
			highLightSelectStyle : {
				fillColor : createColorFromHex("#FA8650"),
				fillOpacity : 0.8,
				strokeColor : createColorFromHex("#3399ff"),
				strokeWidth : 4
			}
		},
		/* 
		 * 查询参数
		 */
		searchParameter : { },
		/* 
		 * 坐标定位参数
		 */
		locatorParameter : {
			// 经纬度 - 经度 - 度
			jdd : '',
			// 经纬度 - 经度 - 分
			jdf : '',
			// 经纬度 - 经度 - 秒
			jdm : '',
			// 经纬度 - 维度 - 度
			wdd : '',
			// 经纬度 - 维度 - 分
			wdf : '',
			// 经纬度 - 维度 - 秒
			wdm : '',
			// 平面坐标 - X
			pmx : '',
			// 平面坐标 - Y
			pmy : '',
			// 地理坐标 - X
			dlx : '',
			// 地理坐标 - Y
			dly : ''
		},
		/**
		 * 是否正在绘制
		 */
		isDrawing:false
	});

	/* 
	 * 定义ArcGIS的绘制模块
	 */
	itfreerarcgiscoreModule.factory('$itfreer_arcgis_core', function($rootScope, $itfreer_core, $gisObject) {
		$itfreer_arcgis_core = {
			/**
			 * 获取要素集的最大视图范围
			 * 
			 * @param { [
			 *            <esri.layer.GraphicLayer>]} features 目标对象
			 * @param {
			 *            <Number>} zoomFactor
			 * @return {esri.geometry.Extent}
			 */
			getMaxExtent : function(features, zoomFactor) {
				if (features.length < 0) {
					return false;
				}
				if (!zoomFactor)
					zoomFactor = 1;
				var extent = new esri.geometry.Extent();  
				//根据第一个不为null的geometry判断geometry类型
				for(var i = 0;i<features.length;i++){
					var _geometry = features[i].geometry;
					if(!_geometry || _geometry == null)
						continue;
					if (_geometry.type == "polygon")
					{
						//将范围进行叠加
						for (var j = 0; j < features.length; j++) {
							if(features[j].geometry)
								if(extent.xmin&&extent.xmax&&extent.ymin&&extent.ymax){
									extent = extent.union(features[j].geometry.getExtent());
								}
								else{
									extent = features[j].geometry.getExtent();
								}
						}
						extent = extent.expand(zoomFactor);
					} else if (_geometry.type == "point") {
						var pointX;
						var pointY;
						var pointXArr = [];
						var pointYArr = [];
						for (var j = 0; j < features.length; j++) {
							if(features[j].geometry){
								pointX = features[j].geometry.x;
								pointY = features[j].geometry.y;
								pointXArr.push(pointX);
								pointYArr.push(pointY);
							}
						}
						var maxX = Math.max.apply(null, pointXArr) + 0.1;
						var minX = Math.min.apply(null, pointXArr) - 0.1;
						var maxY = Math.max.apply(null, pointYArr) + 0.1;
						var minY = Math.min.apply(null, pointYArr) - 0.1;
						extent = new esri.geometry.Extent(minX, minY, maxX, maxY,
								_geometry.spatialReference).expand(zoomFactor);
					} else {
						//将范围进行叠加
						for (var j = 0; j < features.length; j++) {
							if(features[j].geometry)
								if(extent.xmin&&extent.xmax&&extent.ymin&&extent.ymax){
									extent = extent.union(features[j].geometry.getExtent());
								}
								else{
									extent = features[j].geometry.getExtent();
								}
						}
						extent = extent.expand(zoomFactor);
					}
					break;
				}
				// 调整返回的extent大小
				var _x = extent.xmax - extent.xmin;
				var _y = extent.ymax - extent.ymin;
				extent.xmax = extent.xmax + (_x / 3);
				extent.xmin = extent.xmin - (_x / 3);
				extent.ymax = extent.ymax + (_y / 3);
				extent.ymin = extent.ymin - (_y / 3);
				extent.spatialReference = $gisObject.map.spatialReference;
				return extent;
			}, 

			/**
			 * 获取Geometry的中心点
			 * 
			 * @function {public} ?
			 * @param {esri.geometry.Geometry}
			 *            geometry - 几何对象
			 * @return point - 点对象
			 */
			getCenter : function(geometry) {
				var _point;
				if (geometry.type == "point") {
					_point = geometry;
				} else if (geometry.type == "polygon") {
					_point = geometry.getExtent().getCenter();
				} else if(geometry.type == "polyline"){
					var ptnArr = geometry.paths[0][geometry.paths[0].length - 1];
					_point = new esri.geometry.Point(ptnArr[0], ptnArr[1], geometry.spatialReference);
				} else {
					_point = geometry.getExtent().getCenter();
				}
				return _point;
			},

			/**
			 * 根据字符串获取Extent对象
			 * 
			 * @function {public} ?
			 */
			getExtentByString : function(extentStr, wkid) {
				var extentArray = extentStr.split(",");
				var extent = new esri.geometry.Extent({
							"xmin" : parseFloat(extentArray[0]),
							"ymin" : parseFloat(extentArray[1]),
							"xmax" : parseFloat(extentArray[2]),
							"ymax" : parseFloat(extentArray[3]),
							"spatialReference" : wkid
						});
				return extent;
			},

			/**
			 * 重新刷新地图
			 * 
			 * @function {public} ?
			 */
			reflashMap : function() {
				if($gisObject.map){
					$gisObject.map.resize(true);
					$gisObject.map.reposition();
				}
			},

			/**
			 * 获取Graphic
			 */
			getGraphic : function(objectid) {
				var graphic = null;
			   	//遍历地图的graphics查找OBJECTID和点击行的OBJECTID相同的Grapphic
			   	for(var i=0;i<$gisObject.map.graphics.graphics.length;i++){
			      	var cGrapphic=$gisObject.map.graphics.graphics[i];
			      	if(cGrapphic.attributes
			      		&& cGrapphic.attributes.OBJECTID==objectid){
			         	graphic=cGrapphic;
			         	break;
			      	}
			   	}
			   	return graphic;
			},

			/**
			 * 获取小气泡Graphic
			 */
			getGraphicByPop : function(objectid, searchName) {
				var graphic = null;
				var keyName = $gisObject.searchParameter[searchName].keyName;
				if(keyName == null || keyName == ""){
					keyName = "OBJECTID";
				}
			   	//遍历地图的graphics查找OBJECTID和点击行的OBJECTID相同的Grapphic
			   	for(var i=0;i<$gisObject.map.graphics.graphics.length;i++){
			      	var cGrapphic=$gisObject.map.graphics.graphics[i];
			      	if(cGrapphic.attributes
			      		&& cGrapphic.attributes[keyName]==objectid
			      		&& cGrapphic.attributes.$ispop && cGrapphic.attributes.$ispop==true
			      		&& cGrapphic.attributes.$searchName && cGrapphic.attributes.$searchName==searchName){
			         	graphic=cGrapphic;
			         	break;
			      	}
			   	}
			   	return graphic;
			},

			/**
			 * 获取查询的要素Graphic
			 */
			getGraphicByFeature : function(objectid, searchName) {
				var graphic = null;
				var keyName = $gisObject.searchParameter[searchName].keyName;
				if(keyName == null || keyName == ""){
					keyName = "OBJECTID";
				}
			   	//遍历地图的graphics查找OBJECTID和点击行的OBJECTID相同的Grapphic
			   	for(var i=0;i<$gisObject.map.graphics.graphics.length;i++){
			      	var cGrapphic=$gisObject.map.graphics.graphics[i];
			      	if(cGrapphic.attributes
			      		&& cGrapphic.attributes[keyName]==objectid
			      		&& cGrapphic.attributes.$isFeature && cGrapphic.attributes.$isFeature==true
			      		&& cGrapphic.attributes.$searchName && cGrapphic.attributes.$searchName==searchName){
			         	graphic=cGrapphic;
			         	break;
			      	}
			   	}
			   	return graphic;
			},

			/**
			 * 把度分秒的经纬度转换成度的经纬度
			 */
			DMSConvertToDegree : function(strcoordinateD, strcoordinateM,
					strcoordinateS) {
				if (!$itfreer_core.validateNum(strcoordinateD)
						|| !$itfreer_core.validateNum(strcoordinateM)
						|| !$itfreer_core.validateNum(strcoordinateS)) {
					return "";
				}
				icoordinateD = parseInt(strcoordinateD);
				icoordinateM = parseInt(strcoordinateM) / 60;
				icoordinateS = parseInt(strcoordinateS) / 3600;
				return icoordinateD + icoordinateM + icoordinateS;
			},

			// 放大
			mapZoomin : function(){
				// $gisObject.map.setMapCursor("default");
				if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
					$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/zoomin.cur),auto");
				}
				
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.activate(esri.toolbars.Navigation.ZOOM_IN);
				}
			},

			// 缩小
			mapZoomout : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
					$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/zoomout.cur),auto");
				}
				
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.activate(esri.toolbars.Navigation.ZOOM_OUT);
				}
			},

			// 平移
			mapPan : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.map)){
					$gisObject.map.setMapCursor("url("+getJsBasePath()+"/arcgis/images/cur/hand.cur),auto");
				}
				try{
					if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
						$gisObject.navToolbar.activate(esri.toolbars.Navigation.PAN);
					}
				}catch(e){
				}
			},

			// 全图
			mapFullextent : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.zoomToFullExtent();
				}
			},

			// 上一视图
			mapToprev : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.zoomToPrevExtent();
				}
			},

			// 下一视图
			mapTonext : function(){
				if(!$itfreer_core.isNullOrUndefined($gisObject.navToolbar)){
					$gisObject.navToolbar.zoomToNextExtent();
				}
			}
		};
		for(f in $itfreer_arcgis_core){
			$rootScope[f] = $itfreer_arcgis_core[f];
		}
		$rootScope.gisObject = $gisObject;
		return $itfreer_arcgis_core;
	});

	/**
	 * gis第一个控制器
	 */
	itfreerarcgiscoreModule.controller('gisFirstRouterCtrl', ['$scope', '$itfreerHttp', '$formObject', '$itfreer_form_core','$state','$wdp','$rootScope',
		function($scope,$itfreerHttp, $formObject, $itfreer_form_core,$state,$wdp,$rootScope){
			$formObject.isMIS = false;
			$itfreer_form_core.destroyForm();
			$itfreer_form_core.destroyEasyui();
		}
	]);

	/**
	 * gis最后一个控制器
	 */
	itfreerarcgiscoreModule.controller('gisLastRouterCtrl', ['$scope', '$itfreerHttp', '$formObject', '$itfreer_form_core',
		function($scope,$state,$itfreerHttp, $formObject, $itfreer_form_core){
			
		}
	]);

	/* 
	 * 加载服务器
	 */
	itfreerarcgiscoreModule.run(function($rootScope, $itfreer_arcgis_core, $gisObject) {
	  	
	});
}(window, angular));